"use strict";

const Base = require("./base");
const moment = require("moment");
const fs = require("fs");
const path = require("path");
const pump = require("mz-modules/pump");

class UploadController extends Base {
    async file() {
        const { ctx } = this;
        const file = ctx.request.files.length > 0 ? ctx.request.files[0] : null;
        if (!file) return this.error("上传失败");
        try {
            const upload_uri = `public/upload/${moment().format("YYYYMMDD")}`;
            const local_uri = `app/${upload_uri}`;
            await ctx.helper.mkdir(local_uri);
            let filename = await ctx.helper.rename(file.filename);
            const source = fs.createReadStream(file.filepath); // 读取临时地址中的上传文件
            const target = fs.createWriteStream(path.join("app/" + upload_uri, filename)); //创建写入流,写入这个地址
            await pump(source, target); // 利用管道将流写入对应的路径
            const url = `http://${ctx.request.headers.host}/${upload_uri}/${filename}`;
            this.success({
                url: url,
                name: file.filename,
            });
        } finally {
            // 需要删除临时文件
            await ctx.cleanupRequestFiles();
        }
    }
    async clear() {
        const { ctx } = this;
        const { filepath } = ctx.request.body || {};
        let file_uri = filepath.match(/([\d]{8}\/[a-zA-Z0-9]+\.pdf)/);
        let file_path = file_uri[0].split("/");
        let folder = file_path[0];
        let filename = file_path[1];
        let local_uri = `app/public/upload/${folder}/${filename}`;
        try {
            let res = await ctx.helper.unlink(local_uri);
            this.success(res);
        } catch (err) {
            this.success(err);
        }
    }
}

module.exports = UploadController;
